﻿namespace Shortcuts.Common
{
    using Microsoft.Phone.Shell;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text.RegularExpressions;

    public class Tiles
    {
        private Tiles()
        {
        }

        public static Tile Get(Settings settings)
        {
            var tiles = new Tiles().GetActiveTiles();
            if (tiles.ContainsKey(settings))
            {
                return tiles[settings];
            }

            return null;
        }

        public static bool IsActived(Settings settings)
        {
            return new Tiles().GetActiveTiles().ContainsKey(settings);
        }

        public static IEnumerable<Tile> ActiveTiles
        {
            get
            {
                return new Tiles().GetActiveTiles().Select(x => x.Value);
            }
        }

        Settings ConvertSettings(Uri navigationUri)
        {
            Match match = PeelingRegex.Match(navigationUri.OriginalString);
            if (match.Success && match.Groups.Count == 2)
            {
                var title = match.Groups[1].Value;

                return (Settings)Enum.Parse(typeof(Settings), title, true);
            }

            return Settings.None;
        }

        IDictionary<Settings, Tile> GetActiveTiles()
        {
            Dictionary<Settings, Tile> tiles = new Dictionary<Settings, Tile>();
            foreach (var tile in ShellTile.ActiveTiles)
            {
                Settings settings = ConvertSettings(tile.NavigationUri);
                if (settings != Settings.None)
                {
                    tiles.Add(settings, settings.ToTile());
                }
            }

            return tiles;
        }

        static Regex PeelingRegex = new Regex(@"settings=(\w+)");
    }
}
